//
//  CZNetWorkTools.swift
//  weibo
//
//  Created by Apple on 16/3/10.
//  Copyright © 2016年 KY. All rights reserved.
//

import UIKit
import AFNetworking

//  请求方式
enum RequestType:String {
    case GET = "GET"
    case POST = "POST"
}

//  网络请求类
class CZNetWorkTools: NSObject {

    //  单例
    static let netWorkTools: CZNetWorkTools = CZNetWorkTools()
    //  回调闭包别名
    typealias netWorkToolsCallBack = ((response: AnyObject?, error: NSError?)->())?
    //  防止init初始化
    private override init() {
        super.init()
    }
    //  抽取AFHTTPSessionManager，懒加载
    private lazy var sessionManager: AFHTTPSessionManager = {
        let sessionManager = AFHTTPSessionManager()
        sessionManager.responseSerializer.acceptableContentTypes?.insert("text/html")
        sessionManager.responseSerializer.acceptableContentTypes?.insert("text/plain")
        return sessionManager
    }()
    
    //  封装上传接口请求
    func requestLoad(url: String, params: AnyObject?, name: String, data: NSData, callBack: netWorkToolsCallBack) {
        // 成功的闭包
        let successClosure = { (dataTask: NSURLSessionDataTask, response: AnyObject?) -> Void in
            callBack?(response: response, error: nil)
        }
        
        let failureClosure = { (dataTask: NSURLSessionDataTask?, error: NSError) -> Void in
            callBack?(response: nil, error: error)
        }
        sessionManager.POST(url, parameters: params, constructingBodyWithBlock: { (formData) -> Void in
            formData.appendPartWithFileData(data, name: name, fileName: "", mimeType: "application/octet-stream")
            }, progress: nil, success: successClosure, failure: failureClosure)
    }
    
    //  封装网络请求
    func requestOperation(requestType: RequestType, url: String, params: AnyObject?, callBack: netWorkToolsCallBack) {
        
        // 成功的闭包
        let successClosure = { (dataTask: NSURLSessionDataTask, response: AnyObject?) -> Void in
            callBack?(response: response, error: nil)
        }
        
        let failureClosure = { (dataTask: NSURLSessionDataTask?, error: NSError) -> Void in
            callBack?(response: nil, error: error)
        }
        
        if requestType == .GET {
            sessionManager.GET(url, parameters: params, progress: nil, success: successClosure, failure: failureClosure)
        } else {
            sessionManager.POST(url, parameters: params, progress: nil, success: successClosure, failure: failureClosure)
        }
        
    }
    
    
}

//  发微博相关接口
extension CZNetWorkTools {
    
    //  发送图片及文字
    func upload(status: String, accessToken: String, img: UIImage, callback: netWorkToolsCallBack) {
        let url = "https://upload.api.weibo.com/2/statuses/upload.json"
        let param = [
            "status": status,
            "access_token": accessToken
        ]

        let data = UIImageJPEGRepresentation(img, 0.7)!
        requestLoad(url, params: param, name: "pic", data: data, callBack: callback)
        
//        sessionManager.POST(url, parameters: param, constructingBodyWithBlock: { (formData) -> Void in
//            //  高质量的发送，data数据太大
//            //let data = UIImagePNGRepresentation(img)!
//            //  传入质量系数去发送图片
//            let data = UIImageJPEGRepresentation(img, 0.7)!
//            //1.上传的二进制，2，服务器对应接口参数3,filename 服务使用生成的名字，一般随便传，服务端一般不会使用，他们自己会处理，mimeType:如果类型不确定可以使用application/octet-stream
//            formData.appendPartWithFileData(data, name: "pic", fileName: "", mimeType: "application/octet-stream")
//            }, progress: nil, success: { (dataTask, response) -> Void in
//                callback?(response: response, error: nil)
//            }) { (dataTask, error) -> Void in
//                callback?(response: nil, error: nil)
//        }
        
            
        
            
    }
    
    //  发送文字
    func update(status: String, accessToken: String, callback: netWorkToolsCallBack) {
        //  发送文字微博
        let url = "https://api.weibo.com/2/statuses/update.json"
        
        let param = [
            "status": status,
            "access_token": accessToken
        ]
        
        CZNetWorkTools.netWorkTools.requestOperation(.POST, url: url, params: param, callBack: callback)
    }
}

//  微博首页相关接口
extension CZNetWorkTools {

    func loadStauts(accessToken: String, sinceId: Int64, maxId: Int64, callBack: netWorkToolsCallBack) {
        let url = "https://api.weibo.com/2/statuses/friends_timeline.json"
        let param = [
            "access_token": CZUserAccountViewModel.sharedAccount.accessToken!,
            "max_id": "\(maxId)",
            "since_id": "\(sinceId)"
        ]
        requestOperation(.GET, url: url, params: param, callBack: callBack)
    }
}

//  oAuth登录相关接口
extension CZNetWorkTools {
    // MARK:    请求accesstoken
    func requestAccesstoken(code: String, callBack: netWorkToolsCallBack) {
        
        let url = "https://api.weibo.com/oauth2/access_token"
        let params = [
            "client_id": Appkey,
            "client_secret": AppSecret,
            "grant_type": "authorization_code",
            "code": code,
            "redirect_uri": Redirect_uri
        ]
        //  获取accesstoken
        requestOperation(.POST, url: url, params: params, callBack: callBack)

    }
    
    //  获取用户数据
    func loadUserInfo(userAccount: CZUserAccount, callBack: netWorkToolsCallBack) {
        let url = "https://api.weibo.com/2/users/show.json"
        let params = [
            "access_token": userAccount.access_token!,
            "uid": userAccount.uid,
        ]
        
        CZNetWorkTools.netWorkTools.requestOperation(.GET, url: url, params: params, callBack: callBack)
        
    }
    

}

